﻿package  {


import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundTransform;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.errors.IOError;
import flash.events.Event;

  public class DynaSound extends Sprite {
        private var bgSong:Sound;
        private var songs:Object;
        private var sTransform:SoundTransform;

          function DynaSound():void {
            songs = new Object();
            sTransform = new SoundTransform(1,0);
            if (ExternalInterface.available) {
                ExternalInterface.marshallExceptions = true;
                ExternalInterface.addCallback("loadSound",loadSound);
                ExternalInterface.addCallback("playSound",playSound);
                ExternalInterface.addCallback("stopSound",stopSound);
                ExternalInterface.addCallback("playSoundManyTimes",playSoundManyTimes);
                ExternalInterface.addCallback("setVolume",setVolume);
                ExternalInterface.call("flashLoadedHandler");
            }
        }
        private function loadSound(songName:String,songPath:String):void {
            songs[songName]={'soundObject': new Sound(new URLRequest(songPath)),
                                            'playingStatus': false,
                                            'channel': null};
        }
        private function playSound(songName:String):void {
            var channel:SoundChannel = songs[songName].soundObject.play(0,0,sTransform);
            songs[songName].channel=channel;
            songs[songName].playingStatus=true;
        }
        private function stopSound(songName:String):void {
            if(songs[songName]){
                if(songs[songName].playingStatus){
                    try{
                    songs[songName].channel.stop();
                    songs[songName].playingStatus=false;
                    } catch(error:IOError){
                        ExternalInterface.call("alert","error IO");
                    }
                }
            }
        }
        private function playSoundManyTimes(songName:String,counter:Number):void {
            var channel:SoundChannel = songs[songName].soundObject.play(0,counter,sTransform);
            songs[songName].channel=channel;
            songs[songName].playingStatus=true;
        }
        private function setVolume(songName:String,volume:Number):void {
            if(songs[songName].playingStatus){
                var transform:SoundTransform = songs[songName].channel.soundTransform;
                transform.volume=volume;
                songs[songName].channel.soundTransform=transform;
            }
            sTransform.volume = volume;
        }
    }
}
